package org.vacoor.xqq.core;

import org.vacoor.xqq.core.bean.AuthcState;
import org.vacoor.xqq.core.bean.ChatToken;
import org.vacoor.xqq.core.bean.Contact;
import org.vacoor.xqq.core.bean.Status;
import org.vacoor.xqq.core.mod.Authenticator;
import org.vacoor.xqq.core.mod.BuddyManager;
import org.vacoor.xqq.core.mod.MessageReceiver;
import org.vacoor.xqq.core.mod.impl.SimpleMessageReceiver;
import org.vacoor.xqq.core.mod.MessageSender;
import org.vacoor.xqq.core.mod.impl.SimpleAuthenticator;
import org.vacoor.xqq.core.msg.EventBusHolder;
import org.vacoor.xqq.core.msg.handler.PrintMessageHandler;

import javax.swing.*;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

/**
 * User: vacoor
 */
public class Demo {
    public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
        final String ACCOUNT = "2214963100@qq.com";
        final String PASSWD = "jiushi123";

        //
        Authenticator authcator = new SimpleAuthenticator(ACCOUNT, PASSWD, Status.BUSY);

        AuthcState authcState = AuthcState.UNKNOWN_ERROR;

        //
        if(! authcator.safetyCheck()) {
            authcState = authcator.doAuthc();
        } else {
            do {
                String verify = (String) JOptionPane.showInputDialog(null, authcState.getMsg(), "Captcha",
                        JOptionPane.YES_NO_OPTION,
                        new ImageIcon(authcator.getCaptcha()),
                        null, null
                );
                if(verify == null) {
                    System.exit(0);
                }
                authcator.setVerify(verify);
            } while ( AuthcState.INVALID_CAPTCHA == (authcState = authcator.doAuthc()) );
        }

        if(AuthcState.SUCCESS != authcState) {
            System.out.println(authcState.getMsg());
            return;
        }


        // 登录成功, 获取 Token
        ChatToken token = authcator.getChatToken();

        // 获取好友管理器
        BuddyManager buddyManager = new BuddyManager(token);
        buddyManager.getOnlineContacts();

        // 注册消息处理器
        EventBusHolder.getEventBus().register(new PrintMessageHandler());

        // 获取消息接收器, 启动消息接收
        MessageReceiver receiver = new SimpleMessageReceiver(token);
        receiver.start();

        // 获取消息发送器
        MessageSender sender = new MessageSender(token);
        System.out.println("发送器OK");
    }
}
